/* list_dir.c */

#include <stdlib.h>
#include <string.h>
#include <dirent.h>

#include "list_dir.h"

static int compare_file_names(const void *p1, const void *p2)
{
  char *s1 = *(char **) p1;
  char *s2 = *(char **) p2;
  
  return strcmp(s1, s2);
}

int list_dir(const char *dir_name, const char *ext, char **list, int max_items)
{
  DIR *dir;
  struct dirent *ent;
  int n;

  dir = opendir(dir_name);
  if (! dir)
    return 1;
  n = 0;
  while (n+1 < max_items && (ent = readdir(dir)) != NULL) {
    int name_len = strlen(ent->d_name);
    if (ext != NULL) {
      int ext_len = strlen(ext);
      
      if (name_len < ext_len || strcmp(ent->d_name + name_len - ext_len, ext) != 0)
        continue;
    }
    list[n] = malloc(name_len + 1);
    strcpy(list[n], ent->d_name);
    n++;
  }
  list[n] = NULL;
  closedir(dir);

  qsort(list, n, sizeof(char *), compare_file_names);
  return 0;
}
